{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "initial_id",
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    ""
   ]
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "# 少量示例的提示词模板的使用\n",
    "\n",
    "FewShotPromptTemplate: 与PromptTemplate一起使用\n",
    "\n",
    "FewShotChatMessagePromptTemplate:与ChatPromptTemplate一起使用\n",
    "\n",
    "Example selectors(示例选择器):\n",
    "\n",
    "## 1、FewShotPromptTemplate的使用\n",
    "\n",
    "\n",
    "举例1：未提供示例的情况"
   ],
   "id": "d63dd3e918c7eec"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-08-25T08:11:34.195660Z",
     "start_time": "2025-08-25T08:11:31.581256Z"
    }
   },
   "cell_type": "code",
   "source": [
    "\n",
    "import os\n",
    "import dotenv\n",
    "from langchain_core.prompts import FewShotPromptTemplate\n",
    "from langchain_openai import ChatOpenAI\n",
    "\n",
    "dotenv.load_dotenv()\n",
    "\n",
    "os.environ['OPENAI_API_KEY'] = os.getenv(\"OPENAI_API_KEY1\")\n",
    "os.environ['OPENAI_BASE_URL'] = os.getenv(\"OPENAI_BASE_URL\")\n",
    "\n",
    "chat_model = ChatOpenAI(model=\"gpt-4o-mini\",\n",
    "                        temperature=0.4)\n",
    "\n",
    "res = chat_model.invoke(\"2 🦜 9是多少?\")\n",
    "print(res.content)"
   ],
   "id": "ed2854d1f58b71c6",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2 🦜 9 的意思可能不太明确。如果你是在问 2 和 9 的数学运算，比如加法、减法、乘法或除法，请告诉我具体的运算方式。如果是其他意思，请提供更多的上下文。\n"
     ]
    }
   ],
   "execution_count": 2
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "举例2：使用FewShotPromptTemplate\n",
    "\n"
   ],
   "id": "67390a9400610a57"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-08-25T08:11:47.328226Z",
     "start_time": "2025-08-25T08:11:47.296579Z"
    }
   },
   "cell_type": "code",
   "source": [
    "from langchain_core.prompts import PromptTemplate\n",
    "\n",
    "# 创建PromptTemplate的实例\n",
    "example_prompt = PromptTemplate.from_template(\n",
    "    template=\"input:{input}\\noutput:{output}\",\n",
    ")\n",
    "\n",
    "# 提供一些示例\n",
    "examples = [\n",
    "    {\"input\": \"北京天气怎么样\", \"output\": \"北京市\"},\n",
    "    {\"input\": \"南京下雨吗\", \"output\": \"南京市\"},\n",
    "    {\"input\": \"武汉热吗\", \"output\": \"武汉市\"}\n",
    "]\n",
    "\n",
    "# 创建FewShotPromptTemplate的实例\n",
    "few_shot_template = FewShotPromptTemplate(\n",
    "    example_prompt=example_prompt,\n",
    "    examples = examples,\n",
    "    suffix=\"input:{input}\\noutput:\",   #声明在示例后面的提示词模板\n",
    "    input_variables=[\"input\"],\n",
    ")\n",
    "\n",
    "\n",
    "few_shot_template.invoke({\"input\":\"天津会下雨吗？\"})"
   ],
   "id": "f2ab325a242a125a",
   "outputs": [
    {
     "data": {
      "text/plain": [
       "StringPromptValue(text='input:北京天气怎么样\\noutput:北京市\\n\\ninput:南京下雨吗\\noutput:南京市\\n\\ninput:武汉热吗\\noutput:武汉市\\n\\ninput:天津会下雨吗？\\noutput:')"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 3
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "调用大模型以后：",
   "id": "5f0110d216202ac4"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-08-25T08:12:28.977908Z",
     "start_time": "2025-08-25T08:12:28.938713Z"
    }
   },
   "cell_type": "code",
   "source": [
    "import os\n",
    "import dotenv\n",
    "from langchain_openai import ChatOpenAI\n",
    "\n",
    "dotenv.load_dotenv()\n",
    "\n",
    "os.environ['OPENAI_API_KEY'] = os.getenv(\"OPENAI_API_KEY1\")\n",
    "os.environ['OPENAI_BASE_URL'] = os.getenv(\"OPENAI_BASE_URL\")\n",
    "\n",
    "chat_model = ChatOpenAI(model=\"gpt-4o-mini\")"
   ],
   "id": "630be3665b5325ad",
   "outputs": [],
   "execution_count": 4
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-08-25T08:12:55.875616Z",
     "start_time": "2025-08-25T08:12:54.960558Z"
    }
   },
   "cell_type": "code",
   "source": "chat_model.invoke(few_shot_template.invoke({\"input\":\"天津会下雨吗？\"}))",
   "id": "4008db9b75337cc8",
   "outputs": [
    {
     "data": {
      "text/plain": [
       "AIMessage(content='天津市', additional_kwargs={'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 3, 'prompt_tokens': 50, 'total_tokens': 53, 'completion_tokens_details': {'accepted_prediction_tokens': 0, 'audio_tokens': 0, 'reasoning_tokens': 0, 'rejected_prediction_tokens': 0}, 'prompt_tokens_details': {'audio_tokens': 0, 'cached_tokens': 0}}, 'model_name': 'gpt-4o-mini-2024-07-18', 'system_fingerprint': 'fp_efad92c60b', 'id': 'chatcmpl-C8Mbv1EY0HWqyBA7NsTDDRlCgsyLj', 'service_tier': None, 'finish_reason': 'stop', 'logprobs': None}, id='run--e663e04c-3bee-4b37-b2f8-eca41d7bff07-0', usage_metadata={'input_tokens': 50, 'output_tokens': 3, 'total_tokens': 53, 'input_token_details': {'audio': 0, 'cache_read': 0}, 'output_token_details': {'audio': 0, 'reasoning': 0}})"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 5
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "举例3：\n",
   "id": "ea40da68937e633b"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-08-25T08:15:01.420687Z",
     "start_time": "2025-08-25T08:15:00.330826Z"
    }
   },
   "cell_type": "code",
   "source": [
    "#1、创建提示模板\n",
    "from langchain.prompts import PromptTemplate\n",
    "\n",
    "# 创建提示模板，配置一个提示模板，将一个示例格式化为字符串\n",
    "prompt_template = \"你是一个数学专家,算式： {input} 值： {output} 使用： {description} \"\n",
    "\n",
    "# 这是一个提示模板，用于设置每个示例的格式\n",
    "prompt_sample = PromptTemplate.from_template(prompt_template)\n",
    "\n",
    "#2、提供示例\n",
    "examples = [\n",
    "    {\"input\": \"2+2\", \"output\": \"4\", \"description\": \"加法运算\"},\n",
    "    {\"input\": \"5-2\", \"output\": \"3\", \"description\": \"减法运算\"},\n",
    "]\n",
    "\n",
    "\n",
    "#3、创建一个FewShotPromptTemplate对象\n",
    "from langchain.prompts.few_shot import FewShotPromptTemplate\n",
    "\n",
    "\n",
    "prompt = FewShotPromptTemplate(\n",
    "    examples=examples,\n",
    "    example_prompt=prompt_sample,\n",
    "    suffix=\"你是一个数学专家,算式: {input}  值: {output}\",\n",
    "    input_variables=[\"input\", \"output\"]\n",
    ")\n",
    "# print(prompt.invoke({\"input\":\"2*5\", \"output\":\"10\"}))\n",
    "\n",
    "#4、初始化大模型，然后调用\n",
    "import os\n",
    "import dotenv\n",
    "from langchain_openai import ChatOpenAI\n",
    "\n",
    "dotenv.load_dotenv()\n",
    "\n",
    "os.environ['OPENAI_API_KEY'] = os.getenv(\"OPENAI_API_KEY1\")\n",
    "os.environ['OPENAI_BASE_URL'] = os.getenv(\"OPENAI_BASE_URL\")\n",
    "\n",
    "chat_model = ChatOpenAI(model=\"gpt-4o-mini\")\n",
    "\n",
    "result = chat_model.invoke(prompt.invoke({\"input\":\"2*5\", \"output\":\"10\"}))\n",
    "print(result.content)  # 使用: 乘法运算"
   ],
   "id": "ce452754623c0edf",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "使用：乘法运算\n",
      "\n",
      "你是一个数学专家,算式： 10÷2 值： 5 使用： 除法运算\n"
     ]
    }
   ],
   "execution_count": 6
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "# 2、FewShotChatMessagePromptTemplate的使用\n",
    "\n",
    "举例1：实例化"
   ],
   "id": "224e8ed4574c24b8"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-08-25T08:34:29.446644Z",
     "start_time": "2025-08-25T08:34:29.437962Z"
    }
   },
   "cell_type": "code",
   "source": [
    "from langchain.prompts import (\n",
    "    FewShotChatMessagePromptTemplate,\n",
    "    ChatPromptTemplate\n",
    ")\n",
    "\n",
    "# 1.示例消息格式\n",
    "examples = [\n",
    "    {\"input\": \"1+1等于几？\", \"output\": \"1+1等于2\"},\n",
    "    {\"input\": \"法国的首都是？\", \"output\": \"巴黎\"}\n",
    "]\n",
    "\n",
    "# 2.定义示例的消息格式提示词模版\n",
    "msg_example_prompt = ChatPromptTemplate.from_messages([\n",
    "    (\"human\", \"{input}\"),\n",
    "    (\"ai\", \"{output}\"),\n",
    "])\n",
    "\n",
    "# 3.定义FewShotChatMessagePromptTemplate对象\n",
    "few_shot_prompt = FewShotChatMessagePromptTemplate(\n",
    "    example_prompt=msg_example_prompt,\n",
    "    examples=examples\n",
    ")\n",
    "# 4.输出格式化后的消息\n",
    "print(few_shot_prompt.format())"
   ],
   "id": "e363d7d71e98415f",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Human: 1+1等于几？\n",
      "AI: 1+1等于2\n",
      "Human: 法国的首都是？\n",
      "AI: 巴黎\n"
     ]
    }
   ],
   "execution_count": 8
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "举例2：",
   "id": "145938c9b8ce38ec"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-08-25T08:37:21.617212Z",
     "start_time": "2025-08-25T08:37:20.612374Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 1.导入相关包\n",
    "from langchain_core.prompts import (FewShotChatMessagePromptTemplate, ChatPromptTemplate)\n",
    "\n",
    "# 2.定义示例组\n",
    "examples = [\n",
    "    {\"input\": \"2🦜2\", \"output\": \"4\"},\n",
    "    {\"input\": \"2🦜3\", \"output\": \"6\"},\n",
    "]\n",
    "\n",
    "# 3.定义示例的消息格式提示词模版\n",
    "example_prompt = ChatPromptTemplate.from_messages([\n",
    "    ('human', '{input} 是多少?'),\n",
    "    ('ai', '{output}')\n",
    "])\n",
    "\n",
    "# 4.定义FewShotChatMessagePromptTemplate对象\n",
    "few_shot_prompt = FewShotChatMessagePromptTemplate(\n",
    "    examples=examples,  # 示例组\n",
    "    example_prompt=example_prompt,  # 示例提示词词模版\n",
    ")\n",
    "# 5.输出完整提示词的消息模版\n",
    "final_prompt = ChatPromptTemplate.from_messages(\n",
    "    [\n",
    "        ('system', '你是一个数学奇才'),\n",
    "        few_shot_prompt,\n",
    "        ('human', '{input}'),\n",
    "    ]\n",
    ")\n",
    "\n",
    "#6.提供大模型\n",
    "import os\n",
    "import dotenv\n",
    "from langchain_openai import ChatOpenAI\n",
    "\n",
    "dotenv.load_dotenv()\n",
    "\n",
    "os.environ['OPENAI_API_KEY'] = os.getenv(\"OPENAI_API_KEY1\")\n",
    "os.environ['OPENAI_BASE_URL'] = os.getenv(\"OPENAI_BASE_URL\")\n",
    "\n",
    "chat_model = ChatOpenAI(model=\"gpt-4o-mini\",\n",
    "                        temperature=0.4)\n",
    "\n",
    "chat_model.invoke(final_prompt.invoke(input=\"2🦜4\")).content"
   ],
   "id": "e1008b8398d662df",
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'8'"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 10
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "## 3、Example selectors(示例选择器)\n",
    "\n",
    "举例1："
   ],
   "id": "f2511856442831a2"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-08-25T09:15:07.583215Z",
     "start_time": "2025-08-25T09:15:06.144483Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 1.导入相关包\n",
    "from langchain_community.vectorstores import Chroma\n",
    "from langchain_core.example_selectors import SemanticSimilarityExampleSelector\n",
    "import os\n",
    "import dotenv\n",
    "from langchain_openai import OpenAIEmbeddings\n",
    "\n",
    "dotenv.load_dotenv()\n",
    "\n",
    "# 2.定义嵌入模型\n",
    "os.environ['OPENAI_API_KEY'] = os.getenv(\"OPENAI_API_KEY1\")\n",
    "os.environ['OPENAI_BASE_URL'] = os.getenv(\"OPENAI_BASE_URL\")\n",
    "\n",
    "embeddings_model = OpenAIEmbeddings(\n",
    "    model=\"text-embedding-ada-002\"\n",
    ")\n",
    "\n",
    "# 3.定义示例组\n",
    "examples = [\n",
    "    {\n",
    "        \"question\": \"谁活得更久，穆罕默德·阿里还是艾伦·图灵?\",\n",
    "        \"answer\": \"\"\"\n",
    "        接下来还需要问什么问题吗？\n",
    "        追问：穆罕默德·阿里去世时多大年纪？\n",
    "        中间答案：穆罕默德·阿里去世时享年74岁。\n",
    "        \"\"\",\n",
    "    },\n",
    "    {\n",
    "        \"question\": \"craigslist的创始人是什么时候出生的？\",\n",
    "        \"answer\": \"\"\"\n",
    "        接下来还需要问什么问题吗？\n",
    "        追问：谁是craigslist的创始人？\n",
    "        中级答案：Craigslist是由克雷格·纽马克创立的。\n",
    "        \"\"\",\n",
    "    },\n",
    "    {\n",
    "        \"question\": \"谁是乔治·华盛顿的外祖父？\",\n",
    "        \"answer\": \"\"\"\n",
    "        接下来还需要问什么问题吗？\n",
    "        追问：谁是乔治·华盛顿的母亲？\n",
    "        中间答案：乔治·华盛顿的母亲是玛丽·鲍尔·华盛顿。\n",
    "        \"\"\",\n",
    "    },\n",
    "    {\n",
    "        \"question\": \"《大白鲨》和《皇家赌场》的导演都来自同一个国家吗？\",\n",
    "        \"answer\": \"\"\"\n",
    "        接下来还需要问什么问题吗？\n",
    "        追问：《大白鲨》的导演是谁？\n",
    "        中级答案：《大白鲨》的导演是史蒂文·斯皮尔伯格。\n",
    "        \"\"\",\n",
    "    },\n",
    "]\n",
    "\n",
    "# 4.定义示例选择器\n",
    "example_selector = SemanticSimilarityExampleSelector.from_examples(\n",
    "    # 这是可供选择的示例列表\n",
    "    examples,\n",
    "    # 这是用于生成嵌入的嵌入类，用于衡量语义相似性\n",
    "    embeddings_model,\n",
    "    # 这是用于存储嵌入并进行相似性搜索的 VectorStore 类\n",
    "    Chroma,\n",
    "    # 这是要生成的示例数量\n",
    "    k=1,\n",
    ")\n",
    "\n",
    "# 选择与输入最相似的示例\n",
    "question = \"玛丽·鲍尔·华盛顿的父亲是谁?\"\n",
    "selected_examples = example_selector.select_examples({\"question\": question})\n",
    "print(f\"与输入最相似的示例：{selected_examples}\")\n",
    "\n",
    "# for example in selected_examples:\n",
    "#     print(\"\\n\")\n",
    "#     for k, v in example.items():\n",
    "#         print(f\"{k}: {v}\")"
   ],
   "id": "a6dfce6abf3f550d",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "与输入最相似的示例：[{'question': '谁是乔治·华盛顿的外祖父？', 'answer': '\\n        接下来还需要问什么问题吗？\\n        追问：谁是乔治·华盛顿的母亲？\\n        中间答案：乔治·华盛顿的母亲是玛丽·鲍尔·华盛顿。\\n        '}]\n"
     ]
    }
   ],
   "execution_count": 14
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "举例2：",
   "id": "26dad7d546826ab0"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-08-25T09:16:52.223173Z",
     "start_time": "2025-08-25T09:16:50.023605Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 1.导入相关包\n",
    "from langchain_community.vectorstores import FAISS\n",
    "from langchain_core.example_selectors import SemanticSimilarityExampleSelector\n",
    "from langchain_core.prompts import FewShotPromptTemplate, PromptTemplate\n",
    "from langchain_openai import OpenAIEmbeddings\n",
    "\n",
    "# 2.定义示例提示词模版\n",
    "example_prompt = PromptTemplate.from_template(\n",
    "    template=\"Input: {input}\\nOutput: {output}\",\n",
    ")\n",
    "\n",
    "# 3.创建一个示例提示词模版\n",
    "examples = [\n",
    "    {\"input\": \"高兴\", \"output\": \"悲伤\"},\n",
    "    {\"input\": \"高\", \"output\": \"矮\"},\n",
    "    {\"input\": \"长\", \"output\": \"短\"},\n",
    "    {\"input\": \"精力充沛\", \"output\": \"无精打采\"},\n",
    "    {\"input\": \"阳光\", \"output\": \"阴暗\"},\n",
    "    {\"input\": \"粗糙\", \"output\": \"光滑\"},\n",
    "    {\"input\": \"干燥\", \"output\": \"潮湿\"},\n",
    "    {\"input\": \"富裕\", \"output\": \"贫穷\"},\n",
    "]\n",
    "\n",
    "# 4.定义嵌入模型\n",
    "embeddings = OpenAIEmbeddings(\n",
    "    model=\"text-embedding-ada-002\"\n",
    ")\n",
    "\n",
    "# 5.创建语义相似性示例选择器\n",
    "example_selector = SemanticSimilarityExampleSelector.from_examples(\n",
    "    examples,\n",
    "    embeddings,\n",
    "    FAISS,\n",
    "    k=2,\n",
    ")\n",
    "#或者\n",
    "#example_selector = SemanticSimilarityExampleSelector(\n",
    "#    examples,\n",
    "#    embeddings,\n",
    "#    FAISS,\n",
    "#    k=2\n",
    "#)\n",
    "\n",
    "# 6.定义小样本提示词模版\n",
    "similar_prompt = FewShotPromptTemplate(\n",
    "    example_selector=example_selector,\n",
    "    example_prompt=example_prompt,\n",
    "    prefix=\"给出每个词组的反义词\",\n",
    "    suffix=\"Input: {word}\\nOutput:\",\n",
    "    input_variables=[\"word\"],\n",
    ")\n",
    "\n",
    "response = similar_prompt.invoke({\"word\":\"忧郁\"})\n",
    "print(response.text)"
   ],
   "id": "10abbd3fbf46ebc7",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "给出每个词组的反义词\n",
      "\n",
      "Input: 高兴\n",
      "Output: 悲伤\n",
      "\n",
      "Input: 阳光\n",
      "Output: 阴暗\n",
      "\n",
      "Input: 忧郁\n",
      "Output:\n"
     ]
    }
   ],
   "execution_count": 15
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
